import React, { useEffect, useState } from 'react'
import { deleteList, editList, getList } from '../../api'
import {
  Button,
  Space,
  Table,
  message as antdMessage,
  Modal,
  Row,
  Col,
  Input,
} from 'antd'
import { debounce } from 'lodash'
import { useLocation, useSearchParams } from 'react-router-dom'
import qs from 'qs'
export interface ListRawState {
  id: string
  title: string
  address: string
  image: string
  type: string
  price: number
}

interface IObject {
  [propsName: string]: string
}

const Index: React.FC = () => {
  const location = useLocation()
  // 1. 容器
  const [list, setList] = useState<ListRawState[]>([])
  // 2. 请求函数
  const fetchList = async () => {
    const resp = await getList(params)
    setList(resp.data.data)
  }
  // 3. 副作用函数
  useEffect(() => {
    fetchList()
  }, [location])
  // 4. 定义列表项
  const columns = [
    {
      key: 'id',
      dataIndex: 'id',
      title: 'id',
    },
    {
      key: 'title',
      dataIndex: 'title',
      title: 'title',
    },
    {
      key: 'image',
      dataIndex: 'image',
      title: 'image',
      render(src: string) {
        return <img src={src} alt="" height={20} />
      },
    },
    {
      key: 'type',
      dataIndex: 'type',
      title: 'type',
    },
    {
      key: 'address',
      dataIndex: 'address',
      title: 'address',
    },
    {
      key: 'price',
      dataIndex: 'price',
      title: 'price',
    },
    {
      key: 'opration',
      title: '操作',
      render(row: ListRawState) {
        return (
          <Space>
            <Button type="primary" onClick={debounce(() => handleEdit(row))}>
              编辑
            </Button>
            <Button
              type="primary"
              danger
              onClick={debounce(() => handleDelete(row.id), 200)}
            >
              删除
            </Button>
          </Space>
        )
      },
    },
  ]
  // 5. 删除
  const handleDelete = async (id: string) => {
    await deleteList(id)
    await fetchList()
    antdMessage.success('删除成功')
  }
  // 6.编辑
  const handleEdit = (row: ListRawState) => {
    // 打开弹框
    openModal()
    // 数据回显
    setEditData({ ...row })
  }
  // 7. 定义弹框状态
  const [open, setOpen] = useState(false)
  const openModal = () => setOpen(true)
  const closeModal = () => setOpen(false)
  // 8. 弹框数据
  const [editData, setEditData] = useState<ListRawState>({
    id: '1',
    title: '2',
    address: '3',
    type: '4',
    image: '5',
    price: 6,
  })
  // 9. 确定修改
  const handleEditOK = async () => {
    closeModal()
    await editList(editData.id, editData)
    await fetchList()
    antdMessage.success('修改成功')
  }
  /*************************** 查询 *************************************/
  const searchParam = qs.parse(location.search.slice(1))

  const [searchParams, setSearchParams] = useSearchParams()
  const [params, setParams] = useState({
    search: (searchParam.search as string) || '',
    type: searchParam.type || '全部',
    // price_lte: 200,
    // price_gte: 100,
  })
  const types = [
    '全部',
    '已下单',
    '已付款',
    '待发货',
    '已发货',
    '已收货',
    '待评价',
  ]
  return (
    <div>
      <div>
        <Row style={{ margin: '10px 0', alignItems: 'center' }}>
          <Col span={2} style={{ textAlign: 'right' }}>
            搜索：{' '}
          </Col>
          <Col span={20}>
            <Input.Search
              value={params.search}
              onChange={(e) =>
                setParams({
                  ...params,
                  search: e.target.value,
                })
              }
            ></Input.Search>
          </Col>
        </Row>
        <Row style={{ margin: '10px 0', alignItems: 'center' }}>
          <Col span={2} style={{ textAlign: 'right' }}>
            类型：
          </Col>
          <Col span={20}>
            <Space>
              {types.map((v, i) => {
                return (
                  <Button
                    key={i}
                    type={v === params.type ? 'primary' : 'default'}
                    onClick={() =>
                      setParams({
                        ...params,
                        type: v,
                      })
                    }
                  >
                    {v}
                  </Button>
                )
              })}
            </Space>
          </Col>
        </Row>
        <Row style={{ margin: '10px 0', alignItems: 'center' }}>
          <Col span={2} style={{ textAlign: 'right' }}></Col>
          <Col span={20}>
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  const obj = Object.assign({}, searchParam as IObject, params)
                  // console.log(obj, searchParam, params)
                  setSearchParams(obj)
                }}
              >
                确定
              </Button>
              <Button type="primary" danger>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      <Table
        pagination={{
          pageSize: 4,
        }}
        dataSource={list}
        columns={columns}
        rowKey={'id'}
      ></Table>

      <Modal
        open={open}
        title="编辑"
        cancelText="取消"
        okText="确定"
        onOk={() => handleEditOK()}
        onCancel={closeModal}
      >
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>ID： </Col>
          <Col span={20}>
            <Input
              value={editData.id}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  id: e.target.value,
                })
              }
              disabled
            />
          </Col>
        </Row>
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>标题： </Col>
          <Col span={20}>
            <Input
              value={editData.title}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  title: e.target.value,
                })
              }
            />
          </Col>
        </Row>
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>图片： </Col>
          <Col span={20}>
            <Input
              value={editData.image}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  image: e.target.value,
                })
              }
            />
          </Col>
        </Row>
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>地址： </Col>
          <Col span={20}>
            <Input
              value={editData.address}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  address: e.target.value,
                })
              }
            />
          </Col>
        </Row>
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>类型： </Col>
          <Col span={20}>
            <Input
              value={editData.type}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  type: e.target.value,
                })
              }
            />
          </Col>
        </Row>
        <Row style={{ alignItems: 'center', margin: '10px 0' }}>
          <Col span={4}>价格： </Col>
          <Col span={20}>
            <Input
              type="number"
              value={editData.price}
              onChange={(e) =>
                setEditData({
                  ...editData,
                  price: +e.target.value,
                })
              }
            />
          </Col>
        </Row>
      </Modal>
    </div>
  )
}

export default Index
